home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 52 / Amiga Format AFCD52 (Issue 136, May 2000).iso / -serious- / programming / c / icu-1.3.1 / icu-bin / include / numfmt.h < prev    next >
C/C++ Source or Header  |  2000-02-23  |  21KB  |  530 lines

  1. /*
  2. ********************************************************************************
  3. *                                                                              *
  4. * COPYRIGHT:                                                                   *
  5. *   (C) Copyright Taligent, Inc.,  1997                                        *
  6. *   (C) Copyright International Business Machines Corporation,  1997-1999           *
  7. *   Copyright (C) 1999 Alan Liu and others. All rights reserved.               *
  8. *   Licensed Material - Program-Property of IBM - All Rights Reserved.         *
  9. *   US Government Users Restricted Rights - Use, duplication, or disclosure    *
  10. *   restricted by GSA ADP Schedule Contract with IBM Corp.                     *
  11. *                                                                              *
  12. ********************************************************************************
  13. *
  14. * File NUMFMT.H
  15. *
  16. * Modification History:
  17. *
  18. *   Date        Name        Description
  19. *   02/19/97    aliu        Converted from java.
  20. *   03/18/97    clhuang     Updated per C++ implementation.
  21. *   04/17/97    aliu        Changed DigitCount to int per code review.
  22. *    07/20/98    stephen        JDK 1.2 sync up. Added scientific support.
  23. *                            Changed naming conventions to match C++ guidelines
  24. *                            Derecated Java style constants (eg, INTEGER_FIELD)
  25. ********************************************************************************
  26. */
  27.  
  28. #ifndef NUMFMT_H
  29. #define NUMFMT_H
  30.  
  31.  
  32. #include "utypes.h"
  33. #include "unistr.h"
  34. #include "format.h"
  35.  
  36. class Locale;
  37.  
  38. /**
  39.  * Abstract base class for all number formats.  Provides interface for
  40.  * formatting and parsing a number.  Also provides methods for
  41.  * determining which locales have number formats, and what their names
  42.  * are.
  43.  * <P>
  44.  * NumberFormat helps you to format and parse numbers for any locale.
  45.  * Your code can be completely independent of the locale conventions
  46.  * for decimal points, thousands-separators, or even the particular
  47.  * decimal digits used, or whether the number format is even decimal.
  48.  * <P>
  49.  * To format a number for the current Locale, use one of the static
  50.  * factory methods:
  51.  * <pre>
  52.  * .   double myNumber = 7.0;
  53.  * .   UnicodeString myString;
  54.  * .   UErrorCode success = U_ZERO_ERROR;
  55.  * .   NumberFormat* nf = NumberFormat::createInstance(success)
  56.  * .   nf->format(myNumber, myString);
  57.  * .   cout << " Example 1: " << myString << endl;
  58.  * </pre>
  59.  * If you are formatting multiple numbers, it is more efficient to get
  60.  * the format and use it multiple times so that the system doesn't
  61.  * have to fetch the information about the local language and country
  62.  * conventions multiple times.
  63.  * <pre>
  64.  * .    UnicodeString myString;
  65.  * .    UErrorCode success = U_ZERO_ERROR;
  66.  * .    nf = NumberFormat::createInstance( success );
  67.  * .    int32_t a[] = { 123, 3333, -1234567 };
  68.  * .    const int32_t a_len = sizeof(a) / sizeof(a[0]);
  69.  * .    myString.remove();
  70.  * .    for (int32_t i = 0; i < a_len; i++) {
  71.  * .        nf->format(a[i], myString);
  72.  * .        myString += " ; ";
  73.  * .    }
  74.  * .    cout << " Example 2: " << myString << endl;
  75.  * </pre>
  76.  * To format a number for a different Locale, specify it in the
  77.  * call to createInstance().
  78.  * <pre>
  79.  * .    nf = NumberFormat::createInstance( Locale::FRENCH, success );
  80.  * </pre>
  81.  * You can use a NumberFormat to parse also.
  82.  * <pre>
  83.  * .   UErrorCode success;
  84.  * .   Formattable result(-999);  // initialized with error code
  85.  * .   nf->parse(myString, result, success);
  86.  * </pre>
  87.  * Use createInstance to get the normal number format for that country.
  88.  * There are other static factory methods available.  Use getCurrency
  89.  * to get the currency number format for that country.  Use getPercent
  90.  * to get a format for displaying percentages. With this format, a
  91.  * fraction from 0.53 is displayed as 53%.
  92.  * <P>
  93.  * You can also control the display of numbers with such methods as
  94.  * getMinimumFractionDigits.  If you want even more control over the
  95.  * format or parsing, or want to give your users more control, you can
  96.  * try casting the NumberFormat you get from the factory methods to a
  97.  * DecimalNumberFormat. This will work for the vast majority of
  98.  * countries; just remember to put it in a try block in case you
  99.  * encounter an unusual one.
  100.  * <P>
  101.  * You can also use forms of the parse and format methods with
  102.  * ParsePosition and FieldPosition to allow you to:
  103.  * <ul type=round>
  104.  *   <li>(a) progressively parse through pieces of a string.
  105.  *   <li>(b) align the decimal point and other areas.
  106.  * </ul>
  107.  * For example, you can align numbers in two ways.
  108.  * <P>
  109.  * If you are using a monospaced font with spacing for alignment, you
  110.  * can pass the FieldPosition in your format call, with field =
  111.  * INTEGER_FIELD. On output, getEndIndex will be set to the offset
  112.  * between the last character of the integer and the decimal. Add
  113.  * (desiredSpaceCount - getEndIndex) spaces at the front of the
  114.  * string.
  115.  * <P>
  116.  * If you are using proportional fonts, instead of padding with
  117.  * spaces, measure the width of the string in pixels from the start to
  118.  * getEndIndex.  Then move the pen by (desiredPixelWidth -
  119.  * widthToAlignmentPoint) before drawing the text.  It also works
  120.  * where there is no decimal, but possibly additional characters at
  121.  * the end, e.g. with parentheses in negative numbers: "(12)" for -12.
  122.  */
  123. class U_I18N_API NumberFormat : public Format {
  124. public:
  125.  
  126.     /**
  127.      * Alignment Field constants used to construct a FieldPosition object.
  128.      * Signifies that the position of the integer part or fraction part of
  129.      * a formatted number should be returned.
  130.      *
  131.      * @see FieldPosition
  132.      */
  133.     enum EAlignmentFields {
  134.         kIntegerField,
  135.         kFractionField,
  136.  
  137.  
  138.     /**
  139.      * These constants are provided for backwards compatibility only,
  140.      * and are deprecated.  Please use the C++ style constants defined above.
  141.      */       
  142.         INTEGER_FIELD        = kIntegerField,
  143.         FRACTION_FIELD        = kFractionField
  144.     };
  145.  
  146.     virtual ~NumberFormat();
  147.  
  148.     /**
  149.      * Return true if the given Format objects are semantically equal.
  150.      * Objects of different subclasses are considered unequal.
  151.      */
  152.     virtual bool_t operator==(const Format& other) const;
  153.  
  154.     /**
  155.      * Format an object to produce a string.  This method handles
  156.      * Formattable objects with numeric types. If the Formattable
  157.      * object type is not a numeric type, then it returns a failing
  158.      * UErrorCode.
  159.      *
  160.      * @param obj           The object to format.
  161.      * @param toAppendTo    Where the text is to be appended.
  162.      * @param pos           On input: an alignment field, if desired.
  163.      *                      On output: the offsets of the alignment field.
  164.      * @param status        Output param filled with success/failure status.
  165.      * @return              The value passed in as toAppendTo (this allows chaining,
  166.      *                      as with UnicodeString::append())
  167.      */
  168.     virtual UnicodeString& format(const Formattable& obj,
  169.                                   UnicodeString& toAppendTo,
  170.                                   FieldPosition& pos,
  171.                                   UErrorCode& status) const;
  172.  
  173.     /**
  174.      * Parse a string to produce an object.  This methods handles
  175.      * parsing of numeric strings into Formattable objects with numeric
  176.      * types.
  177.      * <P>
  178.      * Before calling, set parse_pos.index to the offset you want to
  179.      * start parsing at in the source. After calling, parse_pos.index
  180.      * is the end of the text you parsed.  If error occurs, index is
  181.      * unchanged.
  182.      * <P>
  183.      * When parsing, leading whitespace is discarded (with successful
  184.      * parse), while trailing whitespace is left as is.
  185.      * <P>
  186.      * See Format::parseObject() for more.
  187.      *
  188.      * @param source    The string to be parsed into an object.
  189.      * @param result    Formattable to be set to the parse result.
  190.      *                  If parse fails, return contents are undefined.
  191.      * @param parse_pos The position to start parsing at. Upon return
  192.      *                  this param is set to the position after the
  193.      *                  last character successfully parsed. If the
  194.      *                  source is not parsed successfully, this param
  195.      *                  will remain unchanged.
  196.      * @return          A newly created Formattable* object, or NULL
  197.      *                  on failure.  The caller owns this and should
  198.      *                  delete it when done.
  199.      */
  200.     virtual void parseObject(const UnicodeString& source,
  201.                              Formattable& result,
  202.                              ParsePosition& parse_pos) const;
  203.  
  204.     /**
  205.      * Format a double or long number. These methods call the NumberFormat
  206.      * pure virtual format() methods with the default FieldPosition.
  207.      *
  208.      * @param number    The value to be formatted.
  209.      * @param output    Output param with the formatted string.
  210.      * @return          A reference to 'output' param.
  211.      */
  212.     UnicodeString& format(  double number,
  213.                             UnicodeString& output) const;
  214.  
  215.     UnicodeString& format(  int32_t number,
  216.                             UnicodeString& output) const;
  217.  
  218.    /**
  219.     * Format a double or long number. Concrete subclasses must implement
  220.     * these pure virtual methods.
  221.     *
  222.     * @param number     The value to be formatted.
  223.     * @param toAppendTo The string to append the formatted string to.
  224.     *                   This is an output parameter.
  225.     * @param pos        On input: an alignment field, if desired.
  226.     *                   On output: the offsets of the alignment field.
  227.     * @return           A reference to 'toAppendTo'.
  228.     */
  229.     virtual UnicodeString& format(double number,
  230.                                   UnicodeString& toAppendTo,
  231.                                   FieldPosition& pos) const = 0;
  232.     virtual UnicodeString& format(int32_t number,
  233.                                   UnicodeString& toAppendTo,
  234.                                   FieldPosition& pos) const = 0;
  235.  
  236.     /**
  237.      * Redeclared Format method.
  238.      */
  239.     UnicodeString& format(const Formattable& obj,
  240.                           UnicodeString& result,
  241.                           UErrorCode& status) const;
  242.  
  243.    /**
  244.     * Return a long if possible (e.g. within range LONG_MAX,
  245.     * LONG_MAX], and with no decimals), otherwise a double.  If
  246.     * IntegerOnly is set, will stop at a decimal point (or equivalent;
  247.     * e.g. for rational numbers "1 2/3", will stop after the 1).
  248.     * <P>
  249.     * If no object can be parsed, index is unchanged, and NULL is
  250.     * returned.
  251.     * <P>
  252.     * This is a pure virtual which concrete subclasses must implement.
  253.     *
  254.     * @param text           The text to be parsed.
  255.     * @param result         Formattable to be set to the parse result.
  256.     *                       If parse fails, return contents are undefined.
  257.     * @param parsePosition  The position to start parsing at on input.
  258.     *                       On output, moved to after the last successfully
  259.     *                       parse character. On parse failure, does not change.
  260.     * @return               A Formattable object of numeric type.  The caller
  261.     *                       owns this an must delete it.  NULL on failure.
  262.     */
  263.     virtual void parse(const UnicodeString& text,
  264.                        Formattable& result,
  265.                        ParsePosition& parsePosition) const = 0;
  266.  
  267.     /**
  268.      * Parse a string as a numeric value, and return a Formattable
  269.      * numeric object. This method parses integers only if IntegerOnly
  270.      * is set.
  271.      *
  272.      * @param text          The text to be parsed.
  273.      * @param result        Formattable to be set to the parse result.
  274.      *                      If parse fails, return contents are undefined.
  275.      * @param status        Success or failure output parameter.
  276.      * @return              A Formattable object of numeric type.  The caller
  277.      *                      owns this an must delete it.  NULL on failure.
  278.      * @see                 NumberFormat::isParseIntegerOnly
  279.      */
  280.     virtual void parse( const UnicodeString& text,
  281.                         Formattable& result,
  282.                         UErrorCode& status) const;
  283.  
  284.     /**
  285.      * Return true if this format will parse numbers as integers
  286.      * only.  For example in the English locale, with ParseIntegerOnly
  287.      * true, the string "1234." would be parsed as the integer value
  288.      * 1234 and parsing would stop at the "." character.  Of course,
  289.      * the exact format accepted by the parse operation is locale
  290.      * dependant and determined by sub-classes of NumberFormat.
  291.      */
  292.     bool_t isParseIntegerOnly(void) const;
  293.  
  294.     /**
  295.      * Sets whether or not numbers should be parsed as integers only.
  296.      * @see isParseIntegerOnly
  297.      */
  298.     virtual void setParseIntegerOnly(bool_t value);
  299.  
  300.     /**
  301.      * Returns the default number format for the current default
  302.      * locale.  The default format is one of the styles provided by
  303.      * the other factory methods: getNumberInstance,
  304.      * getCurrencyInstance or getPercentInstance.  Exactly which one
  305.      * is locale dependant.
  306.      */
  307.     static NumberFormat* createInstance(UErrorCode&);
  308.  
  309.     /**
  310.      * Returns the default number format for the specified locale.
  311.      * The default format is one of the styles provided by the other
  312.      * factory methods: getNumberInstance, getCurrencyInstance or
  313.      * getPercentInstance.  Exactly which one is locale dependant.
  314.      */
  315.     static NumberFormat* createInstance(const Locale& inLocale,
  316.                                         UErrorCode&);
  317.  
  318.     /**
  319.      * Returns a currency format for the current default locale.
  320.      */
  321.     static NumberFormat* createCurrencyInstance(UErrorCode&);
  322.  
  323.     /**
  324.      * Returns a currency format for the specified locale.
  325.      */
  326.     static NumberFormat* createCurrencyInstance(const Locale& inLocale,
  327.                                                 UErrorCode&);
  328.  
  329.     /**
  330.      * Returns a percentage format for the current default locale.
  331.      */
  332.     static NumberFormat* createPercentInstance(UErrorCode&);
  333.  
  334.     /**
  335.      * Returns a percentage format for the specified locale.
  336.      */
  337.     static NumberFormat* createPercentInstance(const Locale& inLocale,
  338.                                                UErrorCode&);
  339.  
  340.     /**
  341.      * Returns a scientific format for the current default locale.
  342.      */
  343.     static NumberFormat* createScientificInstance(UErrorCode&);
  344.  
  345.     /**
  346.      * Returns a scientific format for the specified locale.
  347.      */
  348.     static NumberFormat* createScientificInstance(const Locale& inLocale,
  349.                                                 UErrorCode&);
  350.  
  351.     /**
  352.      * Get the set of Locales for which NumberFormats are installed.
  353.      */
  354.     static const Locale* getAvailableLocales(int32_t& count);
  355.  
  356.     /**
  357.      * Returns true if grouping is used in this format. For example,
  358.      * in the English locale, with grouping on, the number 1234567
  359.      * might be formatted as "1,234,567". The grouping separator as
  360.      * well as the size of each group is locale dependant and is
  361.      * determined by sub-classes of NumberFormat.
  362.      * @see setGroupingUsed
  363.      */
  364.     bool_t isGroupingUsed(void) const;
  365.  
  366.     /**
  367.      * Set whether or not grouping will be used in this format.
  368.      * @see getGroupingUsed
  369.      */
  370.     virtual void setGroupingUsed(bool_t newValue);
  371.  
  372.     /**
  373.      * Returns the maximum number of digits allowed in the integer portion of a
  374.      * number.
  375.      * @see setMaximumIntegerDigits
  376.      */
  377.     int32_t getMaximumIntegerDigits(void) const;
  378.  
  379.     /**
  380.      * Sets the maximum number of digits allowed in the integer portion of a
  381.      * number. maximumIntegerDigits must be >= minimumIntegerDigits.  If the
  382.      * new value for maximumIntegerDigits is less than the current value
  383.      * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
  384.      * the new value.
  385.      *
  386.      * @see getMaximumIntegerDigits
  387.      */
  388.     virtual void setMaximumIntegerDigits(int32_t newValue);
  389.  
  390.     /**
  391.      * Returns the minimum number of digits allowed in the integer portion of a
  392.      * number.
  393.      * @see setMinimumIntegerDigits
  394.      */
  395.     int32_t getMinimumIntegerDigits(void) const;
  396.  
  397.     /**
  398.      * Sets the minimum number of digits allowed in the integer portion of a
  399.      * number. minimumIntegerDigits must be <= maximumIntegerDigits.  If the
  400.      * new value for minimumIntegerDigits exceeds the current value
  401.      * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
  402.      * the new value.
  403.      * @see getMinimumIntegerDigits
  404.      */
  405.     virtual void setMinimumIntegerDigits(int32_t newValue);
  406.  
  407.     /**
  408.      * Returns the maximum number of digits allowed in the fraction portion of a
  409.      * number.
  410.      * @see setMaximumFractionDigits
  411.      */
  412.     int32_t getMaximumFractionDigits(void) const;
  413.  
  414.     /**
  415.      * Sets the maximum number of digits allowed in the fraction portion of a
  416.      * number. maximumFractionDigits must be >= minimumFractionDigits.  If the
  417.      * new value for maximumFractionDigits is less than the current value
  418.      * of minimumFractionDigits, then minimumFractionDigits will also be set to
  419.      * the new value.
  420.      * @see getMaximumFractionDigits
  421.      */
  422.     virtual void setMaximumFractionDigits(int32_t newValue);
  423.  
  424.     /**
  425.      * Returns the minimum number of digits allowed in the fraction portion of a
  426.      * number.
  427.      * @see setMinimumFractionDigits
  428.      */
  429.     int32_t getMinimumFractionDigits(void) const;
  430.  
  431.     /**
  432.      * Sets the minimum number of digits allowed in the fraction portion of a
  433.      * number. minimumFractionDigits must be <= maximumFractionDigits.   If the
  434.      * new value for minimumFractionDigits exceeds the current value
  435.      * of maximumFractionDigits, then maximumIntegerDigits will also be set to
  436.      * the new value
  437.      * @see getMinimumFractionDigits
  438.      */
  439.     virtual void setMinimumFractionDigits(int32_t newValue);
  440.  
  441. public:
  442.  
  443.     /**
  444.      * Return the class ID for this class.  This is useful only for
  445.      * comparing to a return value from getDynamicClassID().  For example:
  446.      * <pre>
  447.      * .   Base* polymorphic_pointer = createPolymorphicObject();
  448.      * .   if (polymorphic_pointer->getDynamicClassID() ==
  449.      * .       Derived::getStaticClassID()) ...
  450.      * </pre>
  451.      * @return The class ID for all objects of this class.
  452.      */
  453.     static UClassID getStaticClassID(void) { return (UClassID)&fgClassID; }
  454.  
  455.     /**
  456.      * Override Calendar
  457.      * Returns a unique class ID POLYMORPHICALLY.  Pure virtual override.
  458.      * This method is to implement a simple version of RTTI, since not all
  459.      * C++ compilers support genuine RTTI.  Polymorphic operator==() and
  460.      * clone() methods call this method.
  461.      * <P>
  462.      * @return The class ID for this object. All objects of a
  463.      * given class have the same class ID.  Objects of
  464.      * other classes have different class IDs.
  465.      */
  466.     virtual UClassID getDynamicClassID(void) const { return getStaticClassID(); }
  467.  
  468. protected:
  469.  
  470.     /**
  471.      * Default constructor for subclass use only.
  472.      */
  473.     NumberFormat();
  474.  
  475.     /**
  476.      * Copy constructor.
  477.      */
  478.     NumberFormat(const NumberFormat&);
  479.  
  480.     /**
  481.      * Assignment operator.
  482.      */
  483.     NumberFormat& operator=(const NumberFormat&);
  484.  
  485. protected:
  486.     static const int32_t fgMaxIntegerDigits;
  487.     static const int32_t fgMinIntegerDigits;
  488.  
  489. private:
  490.     static char fgClassID;
  491.  
  492.     enum EStyles {
  493.         kNumberStyle,
  494.         kCurrencyStyle,
  495.         kPercentStyle,
  496.         kScientificStyle,
  497.         kStyleCount // ALWAYS LAST ENUM: number of styles
  498.     };
  499.  
  500.     static NumberFormat* createInstance(const Locale& desiredLocale, EStyles choice, UErrorCode& success);
  501.  
  502.     static const int32_t         fgNumberPatternsCount;
  503.     static const UnicodeString     fgLastResortNumberPatterns[];
  504.  
  505.     bool_t      fGroupingUsed;
  506.     int32_t     fMaxIntegerDigits;
  507.     int32_t     fMinIntegerDigits;
  508.     int32_t     fMaxFractionDigits;
  509.     int32_t     fMinFractionDigits;
  510.     bool_t      fParseIntegerOnly;
  511. };
  512.  
  513. // -------------------------------------
  514.  
  515. inline bool_t
  516. NumberFormat::isParseIntegerOnly() const
  517. {
  518.     return fParseIntegerOnly;
  519. }
  520.  
  521. inline UnicodeString&
  522. NumberFormat::format(const Formattable& obj,
  523.                      UnicodeString& result,
  524.                      UErrorCode& status) const {
  525.     return Format::format(obj, result, status);
  526. }
  527.  
  528. #endif // _NUMFMT
  529. //eof
  530.